package com.aispeech.task.api.controller.base;

import com.aispeech.task.common.data.enums.APICode;
import com.aispeech.task.common.data.vo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class APIExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public ResponseEntity<Object> handle(HttpServletRequest request, Exception ex) {
        String remoteAddress = "";
        if (request != null) {
            remoteAddress = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddress == null || "".equals(remoteAddress)) {
                remoteAddress = request.getRemoteAddr();
            }
        }

        String error = String.format("[ APIExceptionHandler.handle ] path: %s, method: %s, from: %s", request.getRequestURL(), request.getMethod(), remoteAddress);

        log.error(error, ex);
        return new ResponseEntity<>(
                Result.fail(APICode.INTERNAL_ERROR),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
        HttpServletRequest request = ((NativeWebRequest) webRequest).getNativeRequest(HttpServletRequest.class);

        String remoteAddress = "";
        if (request != null) {
            remoteAddress = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddress == null || "".equals(remoteAddress)) {
                remoteAddress = request.getRemoteAddr();
            }
        }

        log.error(String.format("path: %s, method: %s, from: %s",
                request.getRequestURL(), request.getMethod(), remoteAddress), ex);

        return new ResponseEntity<>(
                Result.fail(
                        status.value(),
                        ex.getMessage()
                ),
                status);
    }
}
